package juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huangjunkai
 * @description
 * @date 2021/7/11
 */

class LTicket {

    // 票数
    private int number = 50;
    // 创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    public void sale() {
        // 上锁
        lock.lock();
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + ":卖出" + (number--) + "剩下：" + number);
        }
        // 解锁
        lock.unlock();

    }
}

public class LSaleTicket {


    public static void main(String[] args) {
        // 2.创建多个线程，调用资源类操作方法
        LTicket lTicket = new LTicket();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    lTicket.sale();
                }
            }
        },"AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    lTicket.sale();
                }
            }
        },"BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    lTicket.sale();
                }
            }
        },"CC").start();
    }
}
